//参数配置
let appConfig = function(){
	//服务器ip、数据库——测试环境
	// var serverIp = 'http://localhost:9080/';
	// var dbName = '[muframe_base_wulu]';
	// var displayLogEnable = true;
	// var version = '4.1.3';
	// var environment = 'localhost'
	
	
	//服务器ip、数据库——生产环境
	var serverIp = 'https://ty.hnztgckj.com/';
	// // var serverIp = 'https://www.jyhzn.top/';
	var dbName = '[muframe_base_wulu]';
	var displayLogEnable = false;
	var version = '4.1.4';
	var environment = 'test'
	
	//默认物录编码
	// var wuLuCodeDefault = '4BDFAAA0468D4A493E23F2064BACF253';
	var wuLuCodeDefault = '';
	//服务器地址
	var serverAddress = serverIp+'api/';
	//主题颜色
	var mainColor = '#3688FF';
	//小程序名称
	var appName = "油箱卫士";
	//小程序功能介绍
	// var appDes = "本应用是西安交通工程学院信息平台，在这里可以发布或寻找校园资源、如闲置物品、失物招领等等。";
	//登录界面底部提示语
	var loginBottomMessage  = "欢迎使用";
	//获取token用户名和密码
	var tokenUserName = "wuLu";
	var tokenPassword = "1234qwer";
	//接口密钥
	var Aeskey = "hgwjGywj*(JEHp03";
	var AesIV = "hgwjGywj*(JEHp03";
	//图片压缩时宽度标准
	var compressImageWidth = 640;
	//网络请求提示时间
	//与mainfest.json配置文件中的networkTimeout时间保存一致
	var requestWaitTime = 10000;
	
	//参数格式化
	var params = {		
			'serverIp':serverIp,
			'serverAddress':serverAddress,
			'displayLogEnable':displayLogEnable,
			// 'WXserver':WXserver,
			'version':version,
			'environment':environment,
			'mainColor':mainColor,
			'dbName':dbName,
			'appName':appName,
			// 'appDes':appDes,
			'tokenUserName':tokenUserName,
			'tokenPassword':tokenPassword,
			'Aeskey':Aeskey,
			'AesIV':AesIV,
			'compressImageWidth':compressImageWidth,
			'requestWaitTime':requestWaitTime,
			'wuLuCodeDefault':wuLuCodeDefault
	}
	// var data=JSON.stringify(params);
	return params;
}
//读取缓存信息
let appStorage = function(keyStr){	
	try {
		const value = uni.getStorageSync(keyStr);
		if (value) {
			return value;
		}	
	} catch (e) {
		return '';
	}			
}
/**
 * 按格式输出当前时间
 */
let nowTime = function(timeData){
	var myDate = new Date();
	var year = myDate.getFullYear();
	var month = myDate.getMonth()+1;
	if (month < 10){ month = "0" + month;}
	var data = myDate.getDate();
	if (data < 10){ data = "0" + data;}		
	var hour = myDate.getHours();
	if (hour < 10){ hour = "0" + hour;}			
	var Minute = myDate.getMinutes();
	if (Minute < 10){ Minute = "0" + Minute;}	
	var Second = myDate.getSeconds();
	if (Second < 10){ Second = "0" + Second;}	
	
	if(timeData=='Y-m-d H:i:s'){
		return year+'-'+month+'-'+data+' '+hour+':'+Minute+':'+Second;
	}else if(timeData=='Y-m-d H:i'){
		return year+'-'+month+'-'+data+' '+hour+':'+Minute;
	}else if(timeData=='Y-m-d'){
		return year+'-'+month+'-'+data;
	}else if(timeData=='YmdHis'){
		return year+month+data+hour+Minute+Second;
	}
}

//判断字符是否为空的方法
let isEmpty = function(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == "null"){
        return true;
    }else{
        return false;
    }
}
//生成从minNum到maxNum的随机数
let randomNum = function(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
		break; 
    } 
} 

//获取token
//这是一个同步方法
let getToken = function(){
	return new Promise((resolve, reject)=>{
		//先获取本地缓存token
		//比对token是否过期，过期则重新获取，未过期直接返回缓存token
		var tokenStorage = appStorage("wuLuToken");	
		if(tokenStorage){
			displayLog("从缓存中读取到token");
			//获取当前时间
			var nowTimeTemp = nowTime('YmdHis');
			//获取token过期时间
			var tokenExipreTime = tokenStorage.exipreTime;
			if(parseInt(nowTimeTemp)<parseInt(tokenExipreTime)){
				resolve(tokenStorage);
			}else{
				displayLog("缓存中token已过期，重新请求服务器获取");
				//重新请求服务器获取
				var params = {
						'username':appConfig().tokenUserName,
						'password':appConfig().tokenPassword
					};	
				//请求参数：json格式
				displayLog("getToken请求数据："+JSON.stringify(params));
				uni.request({ 
					url:  appConfig().serverIp+'getToken',
					data: params,
					method : "POST",
					header : {'content-type':'application/x-www-form-urlencoded'},				
					success: data => {
						//返回参数：json格式
						displayLog("getToken返回数据："+JSON.stringify(data));
						if (data.statusCode == 200) {
							if(data.data.message.indexOf("认证成功") != -1){
								//将token和exipreTime存入缓存
								uni.setStorage({
									key: 'wuLuToken',
									data: data.data.data,
									success: function () {	
										displayLog("缓存token和exipreTime成功："+JSON.stringify(data.data.data));
										resolve(data.data.data);
									}
								});
							}else{
								displayLog(JSON.stringify(data.data.message));
							}
						}else{
							uni.showToast({title: "发生错误，请重试",icon: 'none'});
						}
					},
					fail: (data, code) => {
						uni.showToast({title: '连接失败...',icon: 'none'});
					}					
				})
			}
		}else{
			displayLog("缓存中没有获取到token，重新请求服务器获取");
			//重新请求服务器获取
			var params = {
					'username':appConfig().tokenUserName,
					'password':appConfig().tokenPassword
				};	
			//请求参数：json格式
			displayLog("getToken请求数据："+JSON.stringify(params));
			uni.request({ 
				url:  appConfig().serverIp+'getToken',
				data: params,
				method : "POST",
				header : {'content-type':'application/x-www-form-urlencoded'},				
				success: data => {
					//返回参数：json格式
					displayLog("getToken返回数据："+JSON.stringify(data));
					if (data.statusCode == 200) {
						if(data.data.message.indexOf("认证成功") != -1){
							//将token和exipreTime存入缓存
							uni.setStorage({
								key: 'wuLuToken',
								data: data.data.data,
								success: function () {	
									displayLog("缓存token和exipreTime成功："+JSON.stringify(data.data.data));
									resolve(data.data.data);
								}
							});
						}else{
							displayLog(JSON.stringify(data.data.message));
						}
					}else{
						uni.showToast({title: "发生错误，请重试",icon: 'none'});
					}
				},
				fail: (data, code) => {
					uni.showToast({title: '连接失败...',icon: 'none'});
				}					
			})
		}
	})
}

//获取token——从服务器获取
let clearTokenAndGetTokenFromServer = function(){
	//先清空本地缓存token
	uni.setStorage({
		key: 'wuLuToken',
		data: data.data.data,
		success: function () {	
			displayLog("缓存token清除成功");
			//重新请求服务器获取
			var params = {
					'username':appConfig().tokenUserName,
					'password':appConfig().tokenPassword
				};	
			//请求参数：json格式
			displayLog("getToken请求数据："+JSON.stringify(params));
			uni.request({ 
				url:  appConfig().serverIp+'getToken',
				data: params,
				method : "POST",
				header : {'content-type':'application/x-www-form-urlencoded'},				
				success: data => {
					//返回参数：json格式
					displayLog("getToken返回数据："+JSON.stringify(data));
					if (data.statusCode == 200) {
						//将token和exipreTime存入缓存
						uni.setStorage({
							key: 'wuLuToken',
							data: data.data.data,
							success: function () {	
								displayLog("缓存token和exipreTime成功："+JSON.stringify(data.data.data));
								return data.data.data;
							}
						});
					}else{
						uni.showToast({title: "发生错误，请重试",icon: 'none'});
					}
				},
				fail: (data, code) => {
					uni.showToast({title: '连接失败...',icon: 'none'});
				}					
			})
		}
	});
}

//控制台console.log显示
let displayLog = function(message){
	if(appConfig().displayLogEnable){
		console.log(message);
		uni.showToast({title: message,icon: 'none'});
	}
}

//生成随机数
let rndNum = function(n){
	var rnd="";
	for(var i=0;i<n;i++)
	    rnd+=Math.floor(Math.random()*10);
	return rnd;
}

// 版本比较
let version_compare = function(v1, v2) {
    //将两个版本号拆成数组
    var arr1 = v1.split('.'),
        arr2 = v2.split('.');
    var minLength=Math.min(arr1.length,arr2.length);
    //依次比较版本号每一位大小
    for (var i = 0; i < minLength; i++) {
        if (parseInt(arr1[i]) != parseInt(arr2[i])) {
            return (parseInt(arr1[i]) > parseInt(arr2[i])) ? 1 : -1;
        }
    }
    // 若前几位分隔相同，则按分隔数比较。
    if (arr1.length == arr2.length) {
        return 0;
    } else {
        return (arr1.length > arr2.length) ? 1 : -1;
    }
}

	
export default {
	appConfig,
	appStorage,
	nowTime,
	isEmpty,
	randomNum,
	getToken,
	clearTokenAndGetTokenFromServer,
	displayLog,
	rndNum,
	version_compare
};
